# rndgen()
# rndgen usando metodo Rejection-sampling
# http://en.wikipedia.org/wiki/Rejection_sampling

# f - target distribution
# g - proposal distribution
# f(x) < M.g(x)

rndgen <- function(m, f, lfdp, M, lmean, lsd)
{
	total <- 0
	v <- rep(0, m)
	for(i in 1:m) {
		while(TRUE) {
			total <- total+1
			x <- rlnorm(1, lmean,lsd)
			h <- M * lfdp(x)
			y. <- runif(1, 0,h)
			y <- f(x)
			if(y. <= y)
				break
		}
		v[i] <- x
	}
print(m/total)
print(1 - m/total)
print(total)
	v
}

rndgen_exp <- function(m, f, M, lambda)
{
	total <- 0
	v <- rep(0, m)
	for(i in 1:m) {
		while(TRUE) {
			total <- total+1
			x <- rexp(1, lambda)
			h <- M * dexp(x,lambda)
			y. <- runif(1, 0,h)
			y <- f(x)
			if(y. <= y)
				break
		}
		v[i] <- x
	}
print(m/total)
print(1 - m/total)
print(total)
	v
}

rndgen_unif <- function(m, f, M, min, max)
{
	total <- 0
	v <- rep(0, m)
	for(i in 1:m) {
		while(TRUE) {
			total <- total+1
			x <- runif(1, min,max)
			h <- M * dunif(x, min,max)

			y. <- runif(1, 0,h)
			y <- f(x)
			if(y. <= y)
				break
		}
		v[i] <- x
	}
#print(m/total)
#print(1 - m/total)
#print(total)
	v
}




####

test_rndgen <- function() {
	N <- 100000
	v <- rep(0, N)
	for(i in 1:N)
		v[i] <- rndgen()
	c(mean(v), sd(v))
}

